import classNames from 'classnames';
import React, { Dispatch, SetStateAction, useContext, useEffect, useRef } from 'react';
import { UseRadioGroupContext } from './radioGroup';

export type RadioLabelType = string | number | undefined;

type RadioSetValueType = Dispatch<SetStateAction<boolean>> | ((value: boolean) => void)

export interface RadioProps {
    value?: boolean
    setValue?: RadioSetValueType
    label?: RadioLabelType
    disabled?: boolean
    className?: string
    children?: React.ReactNode
}

const Radio: React.FC<RadioProps> = (props) => {

    const { className, children, label, value, setValue, disabled } = props;

    const checked = useRef<boolean>(false);

    const { radioGroupValue, setGroupValue, onRadioGroupChange } = useContext(UseRadioGroupContext);

    const classes = classNames('yulang-radio-container', className, 'yulang-radio-cursor');

    const styles = () => {
        return { "--cursor--": disabled ? 'not-allowed' : 'pointer' } as React.CSSProperties
    }

    const inputClasses = classNames('yulang-radio-input', {
        checked: checked.current || value
    })

    const handleClick = () => {
        if (disabled) {
            return false;
        }
        setGroupValue && setGroupValue(label);
        onRadioGroupChange && onRadioGroupChange(label);
        checked.current = !checked.current;
        setValue && setValue(!value);
    }

    useEffect(() => {
        if (typeof radioGroupValue === 'boolean') {
            checked.current = (label === radioGroupValue);
        }
    })

    return <div className={classes} style={styles()} onClick={() => handleClick()}>
        <div className={'yulang-radio-input-container'}>
            <div className={inputClasses}></div>
        </div>
        <div className={'yulang-radio-label'}>{children}</div>
    </div>
}

Radio.defaultProps = {
    disabled: false,
}

Radio.displayName = "Radio";

export default Radio;